package labuladong.leetcode.editor.cn._03binarytree.ch00;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class _144_BinaryTreePreorderTraversal {

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        /* 动态规划思路 */
        // 定义：输入一个节点，返回以该节点为根的二叉树的前序遍历结果
        public List<Integer> preorderTraversal(TreeNode root) {
            LinkedList<Integer> res = new LinkedList<>();
            if (root == null) {
                return res;
            }
            // 前序遍历结果特点：第一个是根节点的值，接着是左子树，最后是右子树
            res.add(root.val);
            res.addAll(preorderTraversal(root.left));
            res.addAll(preorderTraversal(root.right));
            return res;
        }

        /* 回溯算法思路 */
        LinkedList<Integer> res = new LinkedList<>();

        // 返回前序遍历结果
        public List<Integer> preorderTraversal2(TreeNode root) {
            traverse(root);
            return res;
        }

        // 二叉树遍历函数
        void traverse(TreeNode root) {
            if (root == null) {
                return;
            }
            // 前序遍历位置
            res.add(root.val);
            traverse(root.left);
            traverse(root.right);
        }
    }

    //leetcode submit region end(Prohibit modification and deletion)
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        Solution solution = new _144_BinaryTreePreorderTraversal().new Solution();

        TreeNode n3 = new TreeNode(3, null, null);
        TreeNode n2 = new TreeNode(2, n3, null);
        TreeNode n1 = new TreeNode(1, null, n2);

//        List<Integer> res = solution.preorderTraversal(n1);
        List<Integer> res = solution.preorderTraversal2(n1);
        System.out.println(Arrays.toString(res.toArray()));
    }
}
